package com.qijian.production.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.annotation.PlugAnn;
import com.qijian.common.annotation.PlugParam;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.FlowablModelApproval;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.ApprovalDescriptionEnum;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.bean.BeanUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.maindata.domain.vo.PointOrderExcel;
import com.qijian.production.domain.PointOrder;
import com.qijian.production.domain.PointOrderItem;
import com.qijian.production.domain.PointOrderItemDetail;
import com.qijian.production.domain.query.PointOrderQuery;
import com.qijian.production.domain.vo.PointOrderItemVo;
import com.qijian.production.domain.vo.PointOrderVo;
import com.qijian.production.service.IPointOrderItemDetailService;
import com.qijian.production.service.IPointOrderItemService;
import com.qijian.production.service.IPointOrderService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 非标准定额申请单Controller
 *
 * @author qijian
 * @date 2023-12-06
 */
@Api(tags = "非标准定额申请单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/business/pointOrder")
public class PointOrderController extends BaseController {

    private final IPointOrderService pointOrderService;

    private final IPointOrderItemService pointOrderItemService;

    private final IPointOrderItemDetailService pointOrderItemDetailService;

    @GetMapping("/list")
    public TableDataInfo list(PointOrderQuery query, Page<PointOrderVo> page) {
        //TODO 权限
        query.setDataScope(true);
        if (CollectionUtil.isNotEmpty(query.getApprovalStatus())){
            if (query.getApprovalStatus().get(0).equals("U")){
                //查看自己发起的
                query.setU(SecurityUtils.getUserId());
                query.setDataScope(null);
            }else if (query.getApprovalStatus().get(0).equals("I")){
                //查看自己审核的
                query.setI(SecurityUtils.getUserId());
                query.setDataScope(null);
            }else if (query.getApprovalStatus().get(0).equals("ALL")){
                //tood 是否包含自己的所有待确认
            }else {
                query.setApprove(query.getApprovalStatus());
            }
        }

        return getDataTable(pointOrderService.pageVo(page, WhereEntityTool.invoke(query)));
    }

    /**
     * 新增非标准定额申请单
     */
//    @PreAuthorize("@ss.hasPermi('maindata:pointOrder:add')")
    @Log(title = "非标准定额申请单新增修改" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult saveOrUpdateOrder(@RequestBody PointOrderVo pointOrderVo) {
        approval(pointOrderVo);
        return AjaxResult.success(pointOrderService.saveOrUpdateOrder(pointOrderVo));
    }

    @Log(title = "导出非标准定额申请单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportPointOrder")
    public void exportPointOrder(PointOrderQuery query, HttpServletResponse response) {
        List<PointOrderVo> list = pointOrderService.selectVoByCondition(WhereEntityTool.invoke(query));
        List<PointOrderExcel> pointOrderExcelList =new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(e->{
                if (CollectionUtil.isNotEmpty(e.getItems())) {
                    for (PointOrderItemVo item : e.getItems()) {
                        if (CollectionUtil.isNotEmpty(item.getDetails())) {
                            for (PointOrderItemDetail detail : item.getDetails()) {
                                PointOrderExcel pointOrderExcel = new PointOrderExcel();
                                BeanUtils.copyProperties(item,pointOrderExcel);
                                BeanUtils.copyProperties(detail,pointOrderExcel);
                                pointOrderExcel.setScNickName(detail.getNickName());
                                pointOrderExcel.setNickName(item.getNickName());
                                pointOrderExcel.setItemRemark(item.getRemark());
                                pointOrderExcel.setRemark(e.getRemark());
                                pointOrderExcel.setWorkCode(item.getWorkCode());
                                pointOrderExcel.setApplyDate(e.getApplyDate());
                                pointOrderExcel.setApplyDeptName(e.getApplyDeptName());
                                pointOrderExcel.setApplyName(e.getApplyName());
                                pointOrderExcel.setNumber(e.getNumber());
                                pointOrderExcel.setDispatchAttr(e.getDispatchAttr());
                                pointOrderExcelList.add(pointOrderExcel);
                            }
                        }
                    }
                }

            });

        }
        new ExcelUtil<>(PointOrderExcel.class).exportExcel(response, pointOrderExcelList, "非标准定额申请单");

    }



    /**
     * 获取非标准定额申请单详细信息
     */
//    @PreAuthorize("@ss.hasAnyPermi('maindata:pointOrder:list,maindata:pointOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(pointOrderService.getVoById(id));
    }

    /**
     * 删除标准定额申请单
     */
    @Log(title = "删除标准定额申请单" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        List<PointOrder> pointOrders = pointOrderService.listByIds(ids);
        if (CollectionUtils.isNotEmpty(pointOrders)) {
            pointOrders.stream().forEach(e->{
                approval(e);
            });
        }
        pointOrderItemService.remove(new LambdaQueryWrapper<PointOrderItem>().in(PointOrderItem::getMainId,ids));
        pointOrderService.removeByIds(ids);
        pointOrderItemDetailService.remove(new LambdaQueryWrapper<PointOrderItemDetail>().in(PointOrderItemDetail::getMainId,ids));
        return AjaxResult.success();

    }

    /**
     * 单据审核
     */
    @Log(title = "非标准定额申请单详细信息", businessType = BusinessType.APPROVAL)
    @PlugAnn(groupClass = FlowablModelApproval.Approval.class, params = {"'point'", "T(com.qijian.common.utils.SecurityUtils).getUserId()", "T(com.qijian.common.utils.SecurityUtils).getDeptId()", "T(com.qijian.common.utils.SecurityUtils).getNickName()","T(com.qijian.common.utils.SecurityUtils).getDeptName()"})
    @GetMapping(value = "/approval/{ids}")
    public AjaxResult approval(@PlugParam @PathVariable List<Long> ids) {
        PointOrder report = new PointOrder();
        ids.stream().forEach(e->{
            PointOrder pointorder = pointOrderService.getById(e);
            if (pointorder.getApplyDeptId() == null) {
                throw new ServiceException("E01: 部门信息为空！");
            }
            if (ObjectUtil.isNull(pointorder)) {
                throw new ServiceException("E01:单据信息错误！");
            } else if (pointorder.getApprovalStatus() == ApprovalDescriptionEnum.B) {
                throw new ServiceException("E01:单据审核中！");
            } else if (pointorder.getApprovalStatus() == ApprovalDescriptionEnum.C) {
                throw new ServiceException("E01:单据已审核！");
            } else if (pointorder.getApprovalStatus() == ApprovalDescriptionEnum.D) {

            }
            report.setId(e);
            report.setApprovalStatus(ApprovalDescriptionEnum.B);
            report.setSubmissionTime(DateUtils.date());
            pointOrderService.updateById(report);
        });
        return  AjaxResult.success();
    }

}
